using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Windows.Forms;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;  // 添加这行
using System.Windows.Controls;  // 添加这行
using System.Threading.Tasks;  // 添加这行
using System.Threading;  // 添加这行
using System;  // 添加这行
using System.Linq;  // 添加这行
using InTheHand.Net;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.Threading;
using System;
using System.Linq;
using System.IO;

namespace BluetoothTrae  // 确保命名空间与 XAML 文件一致
{
    public partial class MainWindow : Window
    {
        private BluetoothClient _bluetoothClient;
        private ObservableCollection<BluetoothDeviceModel> _devices;
        private bool _isScanning;

        // 在类的成员变量部分添加
        private Microsoft.Win32.OpenFileDialog openFileDialog;

        // 在构造函数中初始化
        public MainWindow()
        {
            InitializeComponent();
            _devices = new ObservableCollection<BluetoothDeviceModel>();
            lvDevices.ItemsSource = _devices;
            _bluetoothClient = new BluetoothClient();
            
            // 初始化文件对话框
            openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Filter = "所有文件|*.*";
        }

        // 添加发送文件的方法
        private async void BtnSendFile_Click(object sender, RoutedEventArgs e)
        {
            if (lvDevices.SelectedItem is BluetoothDeviceModel selectedDevice)
            {
                if (!selectedDevice.IsPaired)
                {
                    MessageBox.Show("请先与设备配对后再发送文件", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (openFileDialog.ShowDialog() == true)
                {
                    try
                    {
                        btnSendFile.IsEnabled = false;
                        var result = await Task.Run(() => SendFile(selectedDevice, openFileDialog.FileName));

                        if (result)
                        {
                            MessageBox.Show("文件发送成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            MessageBox.Show("文件发送失败！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"发送文件时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    finally
                    {
                        btnSendFile.IsEnabled = true;
                    }
                }
            }
        }

        private bool SendFile(BluetoothDeviceModel device, string filePath)
        {
            try
            {
                var btAddress = InTheHand.Net.BluetoothAddress.Parse(device.Address);
                
                // 使用 ObexWebRequest 发送文件
                var uri = new Uri($"obex://{btAddress}/{Path.GetFileName(filePath)}");
                var request = new ObexWebRequest(uri);
                
                // 设置请求参数
                request.Method = "PUT";
                request.ContentType = "application/octet-stream";
                request.ReadFile(filePath);

                using (var response = (ObexWebResponse)request.GetResponse())
                {
                    // 检查具体的响应状态
                    if (response.StatusCode == ObexStatusCode.OK || 
                        response.StatusCode == ObexStatusCode.Continue || 
                        response.StatusCode == ObexStatusCode.Created)
                    {
                        return true;
                    }
                    
                    MessageBox.Show($"传输失败，状态码：{response.StatusCode}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }
        private async void BtnScan_Click(object sender, RoutedEventArgs e)
        {
            _devices.Clear();
            btnScan.IsEnabled = false;
            btnStopScan.IsEnabled = true;
            _isScanning = true;
    
            await Task.Run(() =>
            {
                try
                {
                    while (_isScanning)
                    {
                        var devices = _bluetoothClient.DiscoverDevices();
                        foreach (var device in devices)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                // 使用 InTheHand.Net.Sockets.BluetoothDeviceInfo 的属性
                                var deviceInfo = new BluetoothDeviceModel
                                {
                                    Name = device.DeviceName ?? "未知设备",
                                    Address = device.DeviceAddress.ToString(),
                                    IsConnected = device.Connected,
                                    IsPaired = device.Authenticated,
                                    DiscoveryTime = DateTime.Now,
                                    IsLowEnergy = false,  // 经典蓝牙设备
                                    Rssi = 0  // 经典蓝牙可能无法获取RSSI值
                                };
    
                                var existingDevice = _devices.FirstOrDefault(d => d.Address == deviceInfo.Address);
                                if (existingDevice != null)
                                {
                                    _devices.Remove(existingDevice);
                                }
                                _devices.Insert(0, deviceInfo);
                            });
                        }
                        Thread.Sleep(1000); // 扫描间隔
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"扫描出错: {ex.Message}");
                }
            });
        }
    
        private void BtnStopScan_Click(object sender, RoutedEventArgs e)
        {
            _isScanning = false;
            btnScan.IsEnabled = true;
            btnStopScan.IsEnabled = false;
        }
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            lvDevices.SelectionChanged += LvDevices_SelectionChanged;
        }

        private void LvDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var isDeviceSelected = lvDevices.SelectedItem != null;
            btnPair.IsEnabled = isDeviceSelected;
            btnSendFile.IsEnabled = isDeviceSelected && 
                (lvDevices.SelectedItem as BluetoothDeviceModel)?.IsPaired == true;
        }
    
        private bool PairDevice(BluetoothDeviceModel selectedDevice)
        {
            try
            {
                // 验证设备地址格式
                if (!InTheHand.Net.BluetoothAddress.TryParse(selectedDevice.Address, out InTheHand.Net.BluetoothAddress btAddress))
                {
                    MessageBox.Show($"无效的蓝牙地址: {selectedDevice.Address}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                var devices = _bluetoothClient.DiscoverDevices();
                var targetDevice = devices.FirstOrDefault(d => d.DeviceAddress == btAddress);

                if (targetDevice != null)
                {
                    if (targetDevice.Authenticated)
                    {
                        return true;
                    }

                    try
                    {
                        // 使用完整的命名空间
                        bool pairResult = InTheHand.Net.Bluetooth.BluetoothSecurity.PairRequest(btAddress, null);
                        
                        if (pairResult)
                        {
                            Thread.Sleep(2000); // 给系统更多时间完成配对
                            
                            // 验证配对结果
                            devices = _bluetoothClient.DiscoverDevices();
                            targetDevice = devices.FirstOrDefault(d => d.DeviceAddress == btAddress);
                            return targetDevice?.Authenticated ?? false;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"配对过程出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("未找到选中的设备，请重新扫描", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"配对过程出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }
    
                private async void BtnPair_Click(object sender, RoutedEventArgs e)
                {
                    if (lvDevices.SelectedItem is BluetoothDeviceModel selectedDevice)
                    {
                        try
                        {
                            btnPair.IsEnabled = false;
                            var result = await Task.Run(() => PairDevice(selectedDevice));
    
                            if (result)
                            {
                                MessageBox.Show($"设备 {selectedDevice.Name} 配对成功！", "配对成功", MessageBoxButton.OK, MessageBoxImage.Information);
                                selectedDevice.IsPaired = true;
                            }
                            else
                            {
                                MessageBox.Show($"设备 {selectedDevice.Name} 配对失败！", "配对失败", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"配对过程出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        finally
                        {
                            btnPair.IsEnabled = true;
                        }
                    }
                }
    }
    public class BluetoothDeviceModel
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public bool IsConnected { get; set; }
        public bool IsPaired { get; set; }
        public DateTime DiscoveryTime { get; set; }
        public bool IsLowEnergy { get; set; }
        public int Rssi { get; set; }
    }
}